﻿#region

using System;
using System.Collections.Generic;
using System.Linq;
using HouseHoldBudget.Core.Data;
using HouseHoldBudget.Core.Entities.User;

#endregion

namespace HouseHoldBudget.Services.Users
{
    public class UserService : IUserService
    {
        #region Readonly & Static Fields

        private readonly IRepository<BudgetUser> _customerRepository;

        #endregion

        #region Constructors

        public UserService(IRepository<BudgetUser> customerRepository)
        {
            _customerRepository = customerRepository;
        }

        #endregion

        #region IUserService Members

        /// <summary>
        /// Validates the user.
        /// </summary>
        /// <param name="loginName">Name of the login.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public BudgetUser ValidateUser(string loginName, string password)
        {
            var query = from c in _customerRepository.Table
                        where c.UserLogin == loginName && c.UserPassword == password && c.IsActive
                        orderby c.Id
                        select c;
            var customer = query.FirstOrDefault();
            return customer;
        }

        /// <summary>
        /// Validates the windows user.
        /// </summary>
        /// <param name="loginName">Name of the login.</param>
        /// <returns></returns>
        public BudgetUser ValidateWindowsUser(string loginName)
        {
            var query = from c in _customerRepository.Table
                        where c.UserLogin == loginName && c.IsActive
                        orderby c.Id
                        select c;
            var customer = query.FirstOrDefault();
            return customer;
        }

        /// <summary>
        /// Gets all user.
        /// </summary>
        /// <returns></returns>
        public List<BudgetUser> GetAllUser(Guid currentUserId, bool exceptMe = false)
        {
            var query = from c in _customerRepository.Table
                        where c.IsActive
                        orderby c.Id
                        select c;

            if (exceptMe)
                query = from c in query
                        where c.Id != currentUserId
                        orderby c.Id
                        select c; 

            var customer = query.ToList();
            return customer;
        }

        /// <summary>
        /// Gets the user by id.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <returns></returns>
        public BudgetUser GetUserById(Guid userId)
        {
            return _customerRepository.GetById(userId);
        }

        #endregion
    }
}